package com.fingard.dsp.bank.directbank.fxb01;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;

import java.util.Calendar;
import java.util.Date;

public class FXB01Transaction extends FXB01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        StringBuilder message = new StringBuilder();
        int succeCount = 0;//查询的总条数
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            //按自然月循环查询
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while (tmpIntDateFrom <= tmpIntDateTo) {
                //每次请求返回的数据条数
                int pageNum = 1;
                boolean tmpQryNext = true;
                int pageSize = this.getBankConfig().getValueAsInt("pageSize", 100);
                int tmpCount = 0;
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                while (tmpQryNext) {
                    JSONObject request = new JSONObject();
                    JSONObject appHeader = new JSONObject();
                    JSONObject body = new JSONObject();
                    FXB01Header header = new FXB01Header();
                    header.transCode = "300130003";
                    header.clientTime = Format.DateTime2Format.format(new Date());
                    header.batchID = p_req7516.reqHeader.transSeqID;
                    header.currentNum = pageNum+"";
                    header.branchId = bankFront.org;
                    writeCommonHeader(request, header);
                    body.put("BASE_ACCT_NO", p_req7516.actNum);
                    body.put("START_DATE", p_req7516.dateFrom);
                    body.put("END_DATE", p_req7516.dateTo);
                    body.put("TRAN_KIND", "A");
                    body.put("HIST_KIND", "0");
                    appHeader.put("PGUP_OR_PGDN","1");//0上翻,1下翻默认为１
                    appHeader.put("TOTAL_NUM",pageSize + "");//数字-1：不进行翻页查询
                    String currentNum = String.valueOf(pageNum-1);
                    appHeader.put("CURRENT_NUM",currentNum);//当前记录号
                    appHeader.put("TOTAL_FLAG","E");//默认EN-不查询总笔数E-查询总记录数
                    String pageEnd = String.valueOf(pageNum+pageSize);
                    appHeader.put("PAGE_START",pageNum);//本页第一笔标志
                    appHeader.put("PAGE_END",pageEnd);//本页最后一笔标志
                    request.put("APP_HEAD", appHeader);
                    request.put("BODY", body);
                    String[] tmpStrRet = sendToBank(request.toJSONString(), p_req7516.reqHeader.transType, p_req7516.reqHeader.transType);

                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        JSONObject reponse = JSONObject.parseObject(tmpStrRet[1]);
                        if (reponse != null) {
                            JSONObject tmpHeader = JSONObject.parseObject(reponse.getString("SYS_HEAD"));
                            JSONArray ret = JSONArray.parseArray(tmpHeader.getString("RET"));
                            if (ret != null && ret.size() > 0) {
                                JSONObject object = JSONObject.parseObject(ret.get(0).toString());
                                String tmprspmsg = object.getString("RET_MSG");
                                String tmprspcod = object.getString("RET_CODE");
                                int totalNum = StringHelper.changeStrToNum(object.getString("TOTAL_ROWS"));
                                if (tmprspcod != null && "000000".equals(tmprspcod)) {
                                    JSONObject tmpBody = JSONObject.parseObject(reponse.getString("BODY"));
                                    JSONArray respArray = JSONArray.parseArray(tmpBody.getString("TRAN_HIST_ARRAY"));
                                    if (respArray != null && respArray.size() > 0) {
                                        for (int i = 0; i < respArray.size(); i++) {
                                            JSONObject respInfoBody = respArray.getJSONObject(i);
                                            succeCount++;
                                            tmpCount++;
                                            RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                            tmpRetDetail.actNum = respInfoBody.getString("BASE_ACCT_NO");
                                            tmpRetDetail.recAccNum = respInfoBody.getString("OTH_BASE_ACCT_NO");//收方账号
                                            tmpRetDetail.recAccName = respInfoBody.getString("OTH_ACCT_DESC");//收方户名
                                            tmpRetDetail.recAccBank = respInfoBody.getString("OTH_BANK_NAME");//收方银行
                                            tmpRetDetail.tranAmt = respInfoBody.getString("TRAN_AMT");//交易金额
                                            tmpRetDetail.accBal = respInfoBody.getString("ACTUAL_BAL_AMT");//账户余额
                                            tmpRetDetail.cdFlag = respInfoBody.getString("CR_DR_MAINT_IND").equals("D") ? "1" : "2";//借贷标志 D:借 C:贷
                                            String tranDate = respInfoBody.getString("TRAN_DATE");//交易日期yyyyMMdd
                                            tmpRetDetail.tranDate = DateHelper.convertD8toD10(tranDate);
                                            String tranTime = respInfoBody.getString("TRAN_TIMESTAMP");//交易时间戳
                                            if (StringHelper.hasAnyChar(tranTime)) {
                                                tmpRetDetail.tranTime = Format.DateTimeFormat.format(new Date(Long.valueOf(tranTime)));
                                            } else {
                                                tmpRetDetail.tranTime = tmpRetDetail.tranDate + " 00:00:00";
                                            }
                                            tmpRetDetail.usage = respInfoBody.getString("NARRATIVE");
                                            tmpRetDetail.abstr = respInfoBody.getString("NARRATIVE");//摘要（对账码）
                                            tmpRetDetail.comment = respInfoBody.getString("TRAN_NOTE");
                                            //  nodeAnalysic(tmpRecord, tmpRetDetail, getCharset());//根据配置将 note 分割赋值给对账码和用途
                                            retAts.writeRetDetailWithoutRespCode(tmpRetDetail);
                                        }
                                    }
                                } else {
                                    message.append("查询时间：").append(Format.Date8Format.format(tmpCalendarFrom.getTime())).append("到").append(Format.Date8Format.format(tmpCalendarTo.getTime())).append(",查询失败：" + tmprspmsg);
                                    tmpQryNext = false;
                                }
                                if(tmpCount < totalNum){
                                    tmpQryNext = true;
                                    pageNum = pageNum*pageSize+1;
                                } else if(tmpCount >= totalNum){
                                    tmpQryNext = false;
                                }
                            } else {
                                message.append("查询时间：").append(Format.Date8Format.format(tmpCalendarFrom.getTime())).append("到").append(Format.Date8Format.format(tmpCalendarTo.getTime())).append(",查询失败：").append("返回数据失败").append(";\r\n");
                                tmpQryNext = false;
                            }
                        } else {
                            message.append("查询时间：").append(Format.Date8Format.format(tmpCalendarFrom.getTime())).append("到").append(Format.Date8Format.format(tmpCalendarTo.getTime())).append(",查询失败：").append(tmpSbMsg).append(";\r\n");
                            tmpQryNext = false;
                        }
                    } else {
                        message.append("查询时间：").append(Format.Date8Format.format(tmpCalendarFrom.getTime())).append("到").append(Format.Date8Format.format(tmpCalendarTo.getTime())).append(",查询失败：").append(tmpStrRet[1]).append(";\r\n");
                        tmpQryNext = false;
                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);//下个月
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            message.append("查询异常：").append(e.getMessage()).append("\r\n");
            retAts.writeRespInfo(message.toString());
            e.printStackTrace();
            retAts.writeEndWithoutInsertDB();
            return retAts;
        } finally {
            if (message.length() > 0) {
                WriteBankLogLn(message.toString());
            }
        }
        if (succeCount == 0 && message.length() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空!");
        } else if (message.length() > 0 && succeCount > 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo(message.toString());
        } else if (succeCount == 0 && message.length() > 0) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(message.toString());
        }
        retAts.writeEndWithoutInsertDB();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        p_req7516.actArea = p_req7515.actArea;
        Date date = new Date();
        p_req7516.dateFrom = Format.Date8Format.format(date);
        p_req7516.dateTo = Format.Date8Format.format(date);
        return d_7516_HisTrans(p_req7516);
    }
}
